﻿using ClosedXML.Excel;
using ClosedXML.Report;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using QMERP.Infrastructure.Tools;

namespace QMERP.Infrastructure.Extensions
{
    public static class ClosedXMLExtension
    {
        /// <summary>
        /// Excel统一转成xlsx再new XLWorkbook返回
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static XLWorkbook ToXLWorkbook(this Stream stream)
        {
            using var oldWorkBook = WorkbookFactory.Create(stream);
            using var newWorkBook = new XSSFWorkbook();
            for (int i = 0; i < oldWorkBook.NumberOfSheets; i++)
            {
                oldWorkBook.GetSheetAt(i).CrossCloneSheet(newWorkBook);
            }
            using var newStream = new MemoryStream();
            newWorkBook.Write(newStream);
            using var ms = new MemoryStream(newStream.ToArray());
            return new XLWorkbook(ms);
        }
        /// <summary>
        /// 列表转Excel报表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static MemoryStream ToExcelReport<T>(this List<T> list)
        {
            Type type = typeof(T);
            string fileName = type.Name.Replace("Response", "");
            var filePath = $"{AppContext.BaseDirectory + ConfigurationUtils.GetSection("ExcelTemplatePathName") + fileName}.xlsx";
            using var stream = new FileStream(filePath, FileMode.Open);
            using var template = new XLTemplate(stream);
            template.AddVariable(ConfigurationUtils.GetSection("ExcelReportAlias"), list);
            template.Generate();
            using var ms = new MemoryStream();
            template.SaveAs(ms);
            return ms;
        }
    }
}
